<template>
    <h1>VUE3.0学习---watch</h1>
    <div class = "test1">
        <h2>监视ref定义的基本数据</h2>
        <p>年龄：{{ age }}</p>
        <button @click="changAge">修改年龄</button><br/>
        <hr/>
        <h2>监视ref定义的对象~启用deep会开启深度监视</h2>
        <p>姓名：{{ person.name }}</p>
        <p>地址：{{ person.addr.bAddr.cAddr }}</p>
        <button @click="changName">修改姓名</button>
        <button @click="changAddr">修改地址</button>
        <button @click="changPerson">修改整个人</button>
    </div>
</template>

<script lang="ts" setup>
   import { watch ,ref} from 'vue';
   let age = ref(10)
   let person = ref({
        name:"张三",
        addr:{bAddr:{cAddr:"钱塘镇"}}
    })
   function changAge(){
    age.value += 10
   }
   const stopWatch = watch(age,(oldValue,newValue) => {
    console.log("监视ref的数据")
    if(age.value > 30){
        // 执行停止监视
        stopWatch()
    }
   })
   function changName(){
    person.value.name += '~'
   }
   function changAddr(){
    person.value.addr.bAddr.cAddr = '太和镇'
   }
   function changPerson(){
    person.value = {name:"李四",addr:{bAddr:{cAddr:"云门镇"}}}
   }
   // 如果启用deep会开启深度监视，就是对象的属性值变了也会被监视
   watch(person,(oldValue,newValue) => {
    console.log(oldValue,newValue)
   },{deep:true})
</script>

<style scoped>
 .test1{
    font-size: 20px;
    color: blue;
    background-color: greenyellow;
    border: 2px solid #007bff; /* 设置边框的宽度和颜色 */
    border-radius: 20px; /* 将四个角变成圆形 */
    width: auto; /* 设置元素的宽度 */
    height: auto; /* 设置元素的高度 */
    padding: 20px;
 }

 button{
    margin: 2px;
 }

</style>